package acwing.bfs;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * 图中点的层次
 *
 * @author yang
 * @date 2021/11/29
 */
public class 图中点的层次 {

    static int N = 100010;
    static int[] h = new int[N];
    static int[] e = new int[N];
    static int[] ne = new int[N];
    static int[] d = new int[N];                //储存每个节点距离起点的距离
    static Queue<Integer> q = new LinkedList<>();
    static boolean[] st = new boolean[N];
    static int idx,n;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        n = in.nextInt();
        int m = in.nextInt();

        for(int i = 0; i < N; i ++) {
            h[i] = -1;
            d[i] = -1;
        }
        for(int i = 0; i < m; i ++) {
            int a = in.nextInt();
            int b = in.nextInt();
            add(a,b);
        }
        System.out.println(bfs(1));
    }

    private static int  bfs(int u) {
        q.add(u);
        d[1] = 0;
        while (q.size() != 0) {
            int t = q.poll();
            for (int i = h[t]; i != -1; i = ne[i]) {
                int j = e[i];
                if (d[j] == -1) {
                    q.add(j);
                    d[j] = d[t] + 1;
                }
            }
        }
        return d[n];
    }

    private static void add(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }

}
